 <template>
  <!-- 活动动态页面主容器 -->
  <div class="activity-feed">
    <!-- 动态导航栏：切换“全部”或“个人动态”视图  新加的v-if="props.showNav" -->
    <div v-if="props.showNav" class="activity-nav-bar">
      <span :class="['nav-item', currentTab === 'all' ? 'active' : '']" @click="switchTab('all')">全部</span>
      <span :class="['nav-item', currentTab === 'user' ? 'active' : '']" @click="switchTab('user')">个人动态</span>
    </div>

    <!-- 浮动按钮：用于打开发布动态的弹窗 -->
    <button class="floating-post-btn" @click="showPostEditor = true">
      <i class="fas fa-plus"></i> 发布动态
    </button>

    <!-- 渲染活动卡片列表 -->
    <div v-for="item in activities" :key="item.id" class="activity-card">
      <ActivityItem
        :activity="item"
        :showActions="currentTab === 'user'"
        @deleted="removeActivity"
        @edit="openEditActivity"
        @comment="openComment"
        @view-media="openMediaViewer"
        @like="likeActivity"
      />
    </div>

    <!-- 发布活动弹窗：控制显示与关闭逻辑 -->
    <div v-if="showPostEditor" class="modal-overlay" @click.self="showPostEditor = false">
      <div class="modal-content">
        <button class="close-modal-btn" @click="showPostEditor = false">
          <i class="fas fa-times"></i> 退出动态发布
        </button>
        <PostEditor @success="fetchActivities" @close="showPostEditor = false" />
      </div>
    </div>

    <!-- 编辑活动弹窗：展示并处理编辑操作 -->
    <div v-if="showEditEditor" class="modal-overlay" @click.self="showEditEditor = false">
      <div class="modal-content">
        <button class="close-modal-btn" @click="showEditEditor = false">
          <i class="fas fa-times"></i> 退出编辑
        </button>
        <EditActivity
            :activity="editingActivity"
            @success="handleEditSuccess"
            @close="showEditEditor = false"
        />
      </div>
    </div>

    <!-- 评论区弹窗：展示指定活动的评论内容 -->
    <div v-if="showComment" class="modal-overlay" @click.self="showComment = false">
      <div class="modal-content">
        <CommentSection :activity-id="commentActivityId" @close="showComment = false" />
      </div>
    </div>

    <!-- 媒体查看器组件：用于预览图片/视频等媒体资源 -->
    <MediaViewer v-if="mediaViewer.show" :mediaList="mediaViewer.list" :initialIndex="mediaViewer.index" @close="mediaViewer.show = false" />
  </div>
</template>


<script setup>
import {defineProps, watch} from 'vue';
import { ref, onMounted } from 'vue';
import axios from 'axios';
import ActivityItem from './ActivityItem.vue';
import PostEditor from './PostEditor.vue';
import EditActivity from './EditActivity.vue';
import CommentSection from './CommentSection.vue';
import MediaViewer from './MediaViewer.vue';
import { currentUser } from '../user';

const activities = ref([]);
const showPostEditor = ref(false);
const showEditEditor = ref(false);
const editingActivity = ref(null);
const showComment = ref(false);
const commentActivityId = ref(null);
const mediaViewer = ref({ show: false, list: [], index: 0 });
const currentTab = ref('all');

const props = defineProps({
  userId: {
    type: [Number, String],
    default: null
  },
  showNav: {
    type: Boolean,
    default: true
  }
});
// 使用 props
console.log('用户ID:', props.userId);
console.log('是否显示导航:', props.showNav);

/**
 * 获取当前用户的 ID。
 * 若 currentUser 中存在有效 ID（且不为默认值 4），则使用该 ID；
 * 否则尝试从 localStorage 的 user 字段中读取；
 * 如果都无效，则返回默认值 4。
 *
 * @returns {number} 当前用户 ID 或默认值 4。
 */
const getUserId = () => {
  const user = JSON.parse(localStorage.getItem('user'));
  return (currentUser.id && currentUser.id !== 4) ? currentUser.id : (user && user.id ? user.id : 4);
};

/**
 * 异步获取活动列表数据，并根据当前标签页类型决定请求地址。
 * 请求完成后重置编辑器与相关状态。
 *
 * @returns {Promise<void>}
 */
async function fetchActivities() {
  let res;
  if (props.userId) {
    // 只获取指定用户的动态
    res = await axios.get(`http://localhost:8085/activity/user/${props.userId}`);
  } else if (currentTab.value === 'all') {
    res = await axios.get('http://localhost:8085/activity/public');
  } else {
    res = await axios.get(`http://localhost:8085/activity/user/${getUserId()}`);
  }
  activities.value = res.data;
  showPostEditor.value = false;
  showEditEditor.value = false;
  editingActivity.value = null;
}

/**
 * 删除指定 ID 的活动项。
 *
 * @param {number} id - 需要删除的活动项 ID。
 */
function removeActivity(id) {
  activities.value = activities.value.filter(a => a.id !== id);
}

/**
 * 打开编辑界面并设置正在编辑的活动对象。
 *
 * @param {Object} activity - 正在被编辑的活动对象。
 */
function openEditActivity(activity) {
  editingActivity.value = activity;
  showEditEditor.value = true;
}

/**
 * 设置评论目标活动 ID 并打开评论区域。
 *
 * @param {Object} activity - 目标活动对象。
 */
function openComment(activity) {
  commentActivityId.value = activity.id;
  showComment.value = true;
}

/**
 * 处理编辑成功事件
 * @param {Object} result - 编辑结果
 */
function handleEditSuccess(result) {
  // 如果需要刷新，则重新获取动态列表
  if (result && result.refresh) {
    fetchActivities();
  }
  showEditEditor.value = false;
  editingActivity.value = null;
}

/**
 * 显示媒体查看器组件，并传入媒体列表及初始索引。
 *
 * @param {Array} list - 媒体资源数组。
 * @param {number} idx - 初始显示的媒体索引。
 */
function openMediaViewer(list, idx) {
  mediaViewer.value = { show: true, list, index: idx };
}

/**
 * 对某个活动执行点赞或取消点赞操作。
 * 使用 toggle-like 接口进行处理，并同步更新 UI 上的点赞数量。
 *
 * @param {Object} activity - 被点赞的目标活动对象。
 * @returns {Promise<void>}
 */
async function likeActivity(activity) {
  if (getUserId() === 4) {
    alert('请先登录');
    return;
  }

  try {
    // 调用新的切换点赞接口
    const response = await axios.post(`http://localhost:8085/activity/${activity.id}/toggle-like`, null, {
      params: { userId: getUserId() }
    });

    if (response.data.success) {
      // 根据返回的点赞状态更新UI
      if (response.data.liked) {
        // 点赞成功，增加计数
        activity.likesCount = (activity.likesCount || 0) + 1;
      } else {
        // 取消点赞，减少计数
        activity.likesCount = Math.max(0, (activity.likesCount || 0) - 1);
      }
    } else {
      alert(response.data.message);
    }
  } catch (e) {
    console.error('点赞操作失败:', e);
    alert('点赞操作失败');
  }
}

/**
 * 切换当前展示的动态标签页。
 * 若切换到“我的”页面但用户未登录（ID=4）时会提示错误信息。
 *
 * @param {'all'|'user'} tab - 新选中的标签页标识符。
 */
function switchTab(tab) {
  if (currentTab.value !== tab) {
    if (tab === 'user' && getUserId() === 4) {
      alert('用户ID为4，无法查看个人动态');
      return;
    }
    currentTab.value = tab;
    fetchActivities();
  }
}

// 页面挂载后自动加载一次活动列表
onMounted(() => {
  fetchActivities();

  // 监听 userId 属性变化，当其变化时重新获取动态
  watch(() => props.userId, (newUserId, oldUserId) => {
    if (newUserId !== oldUserId) {
      fetchActivities();
    }
  });
});

</script>

<style scoped>
.activity-feed {
  width: 850px;
  margin: 0 auto;
  padding: 0 0 80px 0;
  background: #fff;
  color: #23232b;
}
.activity-card {
  margin-bottom: 24px;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(44,62,80,0.08);
  background: #fff;
  padding: 0 0 8px 0;
  width: 100%;
  margin-left: 0;
  margin-right: 0;
}
.floating-post-btn {
  position: fixed;
  bottom: 36px;
  right: 60px;
  z-index: 100;
  background: linear-gradient(90deg, #43484e 0%, #23272b 100%);
  color: #fff;
  border: none;
  border-radius: 18px;
  box-shadow: 0 4px 16px rgba(52,152,219,0.10);
  font-size: 20px;
  font-weight: 500;
  padding: 16px 44px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
}
.floating-post-btn:hover {
  background: linear-gradient(90deg, #23272b 0%, #43484e 100%);
  box-shadow: 0 6px 24px rgba(52,152,219,0.16);
}
.floating-post-btn i {
  font-size: 22px;
  margin-right: 6px;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}
.modal-content {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 16px rgba(44,62,80,0.18);
  width: 95vw;
  max-width: 520px;
  max-height: 90vh;
  overflow: visible;
  margin: 0 auto;
  padding: 24px 18px 18px 18px;
  position: relative;
  box-sizing: border-box;
}
.close-modal-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background: none;
  border: none;
  color: #b0b3c6;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 6px;
  padding: 4px 10px;
  transition: background 0.2s, color 0.2s;
}
.close-modal-btn:hover {
  background: #f0f2f5;
  color: #3498db;
}
@media (max-width: 768px) {
  .activity-feed {
    padding: 12px 2px 80px 2px;
  }
  .floating-post-btn {
    bottom: 18px;
    right: 18px;
    font-size: 16px;
    padding: 10px 18px;
  }
  .modal-content {
    padding: 12px 6px 8px 6px;
  }
}
.activity-nav-bar {
  width: 850px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  align-items: center;
  gap: 40px;
  height: 56px;
  border-bottom: 1.5px solid #f0f0f0;
  margin-bottom: 18px;
  margin-top: 32px;
  font-size: 20px;
  font-weight: 500;
  background: #fff;
  border-radius: 14px 14px 0 0;
  box-shadow: 0 2px 12px rgba(44,62,80,0.08);
  position: relative;
  padding: 0 32px;
  z-index: 2;
}
.nav-item {
  cursor: pointer;
  padding: 0 28px;
  height: 56px;
  display: flex;
  align-items: center;
  color: #888;
  font-weight: 400;
  background: transparent;
  border: none;
  outline: none;
  position: relative;
  transition: color 0.2s, background 0.2s;
  border-radius: 12px 12px 0 0;
}
.nav-item.active {
  color: #2196f3;
  font-weight: bold;
  background: #fff;
}
.nav-item.active::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 60%;
  min-width: 24px;
  max-width: 40px;
  height: 2.5px;
  background: #2196f3;
  border-radius: 2px 2px 2px 2px;
  box-shadow: 0 2px 8px rgba(33,150,243,0.10);
}
.nav-item:not(.active):hover {
  background: #f7faff;
  color: #2196f3;
}
@media (max-width: 900px) {
  .activity-feed, .activity-nav-bar {
    width: 100% !important;
    min-width: 0;
    padding-left: 0;
    padding-right: 0;
  }
}
</style> 